package sample

import (
	"database/sql"
	"gorm.io/gorm"
	"organoid_public/domain/sample/model"
	"organoid_public/domain/sample/repository"
	"organoid_public/infrastructure/db"
	"organoid_public/infrastructure/db/gormclient"
	"strings"
)

type BrowseRepository struct {
	db *gorm.DB
}

func NewBrowseRepository(db db.DefaultDb) repository.Browse {
	return &BrowseRepository{
		db: db,
	}
}

func (h *BrowseRepository) GeneralPageList(param *repository.GeneralListParams) (*gormclient.PageList[model.BrowseGeneral], error) {
	dbInstance := h.db
	if param.Keywords != "" {
		dbInstance = dbInstance.Where("sample_id like @keywords or organoid like @keywords or origin like @keywords or species like @keywords or "+
			"culture_technique like @keywords or culture_days like @keywords or biomarkers like @keywords or applications like @keywords or culture_condition like @keywords", sql.Named("keywords", "%"+param.Keywords+"%"))
	}
	if param.Organoid != "" {
		dbInstance = dbInstance.Where("organoid in ?", strings.Split(param.Organoid, ","))
	}
	if param.Origin != "" {
		dbInstance = gormclient.MultiWhereOrFindInSet(dbInstance, "origin", param.Origin)
	}
	if param.Species != "" {
		dbInstance = gormclient.MultiWhereOrFindInSet(dbInstance, "species", param.Species)
	}
	if param.CultureTechnique != "" {
		dbInstance = gormclient.MultiWhereOrFindInSet(dbInstance, "culture_technique", param.CultureTechnique)
	}
	if param.Biomarker != "" {
		dbInstance = dbInstance.Where("biomarker like ?", "%"+param.Biomarker+"%")
	}
	if param.Applications != "" {
		dbInstance = gormclient.MultiWhereOrFindInSet(dbInstance, "applications", param.Applications)
	}
	if param.Test != "" {
		tests := strings.Split(param.Test, ",")
		for _, test := range tests {
			if test == "geneEditing" {
				dbInstance = dbInstance.Where("test_gene_editing != ''")
			} else if test == "imaging" {
				dbInstance = dbInstance.Where("test_imaging != ''")
			} else if test == "coCulture" {
				dbInstance = dbInstance.Where("test_co_culture != ''")
			} else if test == "multiOmics" {
				dbInstance = dbInstance.Where("test_multi_omics != ''")
			} else if test == "xenograft" {
				dbInstance = dbInstance.Where("test_xenograft != ''")
			}
		}
	}
	if param.CultureConditions != "" {
		dbInstance = dbInstance.Where("culture_condition like ?", "%"+param.CultureConditions+"%")
	}
	if param.Endpoints != "" {
		dbInstance = dbInstance.Where("endpoints like ?", "%"+param.Endpoints+"%")
	}
	if param.Characteristics != "" {
		dbInstance = dbInstance.Where("characteristics like ?", "%"+param.Characteristics+"%")
	}
	if param.Functions != "" {
		dbInstance = dbInstance.Where("functions like ?", "%"+param.Functions+"%")
	}
	if param.DiseaseModeling != "" {
		dbInstance = dbInstance.Where("disease_modeling like ?", "%"+param.DiseaseModeling+"%")
	}
	return gormclient.GetPageList[model.BrowseGeneral](dbInstance, param.Pagination)
}
